package com.simple.microservices.commons.validator;

import cn.hutool.core.util.PhoneUtil;
import com.simple.microservices.commons.annotation.Username;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author HYF
 * @ClassName 自定义校验用户名UsernameValidator
 * @date 2021年11月15日 11:51 上午
 */
@Component
public class UsernameValidator implements ConstraintValidator<Username, String> {

    @Override
    public void initialize(Username constraintAnnotation) {
    }

    @Override
    public boolean isValid(String username, ConstraintValidatorContext constraintValidatorContext) {
        if(StringUtils.isNotEmpty(username)){
            //获取默认提示信息
            String defaultConstraintMessageTemplate = constraintValidatorContext.getDefaultConstraintMessageTemplate();
            //禁用默认提示信息
            constraintValidatorContext.disableDefaultConstraintViolation();
            //设置提示语
            constraintValidatorContext.buildConstraintViolationWithTemplate(defaultConstraintMessageTemplate).addConstraintViolation();
            String emailRegex = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            String phoneRegex = "^1(3|4|5|7|8)\\d{9}$";
            if (!username.matches(emailRegex)){
                return PhoneUtil.isPhone(username);
            }
            return true;
        }
        return true;
    }
}